<!--
 * @Author: wang_sheshe
 * @Date: 2021-05-20 10:43:48
 * @LastEditTime: 2021-08-09 18:53:38
 * @Description: 设备维护提交页
-->
<template>
	<article class="bg_4dbfae tourTaskPage">
		<!-- 头组件 -->
		<!-- <van-nav-bar title="登记信息"  left-arrow @click-left="back"></van-nav-bar> -->
		<Theader :title="title">
			<template slot="header_arrow">
				<van-icon size="25" name="arrow-left" />
			</template>
		</Theader>
		<div class="title-time">
			<span>本次维护时长：</span>
			<label style="color:#FA5151;">2小时54分</label>
		</div>

		<div class="content">
			<div class="doc-wrapper">
				<van-cell class="item-title" is-link @click="arrowDirection" :arrow-direction="baseV">
					<template slot="title">
						<van-image :src="icon.iconTitle" width="20" height="20"></van-image>
						<span style="margin-left: 0.4rem;">基本要求</span>
					</template>
				</van-cell>
				<div v-show="baseV=='down'">
					<van-field
						label="开始时间:" 
						:border="false"  
						readonly 
						v-model="registData.startTime" 
					>
						<template slot="right-icon">
							<van-image style="position: relative;top: 0.2rem;"
							@click="isDatePicker=true"  width="20" height="20" :src="icon.iconDate"/>
						</template>
					</van-field> 

					<van-field
						label="结束时间:" 
						:border="false"  
						readonly 
						v-model="registData.endTime" 
					>
						<template slot="right-icon">
							<van-image style="position: relative;top: 0.2rem;"
							@click="isDatePicker=true"  width="20" height="20" :src="icon.iconDate"/>
						</template>
					</van-field>

					<van-field class="sign-right"
						label="工作人员签名:" 
						:border="false"  
						readonly 
						is-link
						arrow-direction="down"
						v-model="registData.endTime" 
					/>

					<van-field class="sign-right"
						label="负责人签名:" 
						:border="false"  
						readonly 
						is-link
						arrow-direction="down"
						v-model="registData.endTime" 
					/>

					<div class="beizhu">
						<div class="left">结论:</div>
						<div class="right">
							<van-field class="textarea-content" v-model.trim="registData.result" rows="2" autosize type="textarea" maxlength="256"
								placeholder="请添加结论"/>
						</div>
					</div>

					<div class="jielun">
						<div class="left">备注:</div>
						<div class="right">
							<van-field class="textarea-content" v-model.trim="registData.remark" rows="2" autosize type="textarea" maxlength="256"
								placeholder="请添加备注" show-word-limit >
							</van-field>
						</div>
					</div>
					
				</div>
			</div>
			<div class="doc-wrapper">
                <van-cell class="item-title"is-link>
                    <template slot="title">
                        <van-image :src="icon.iconTitle" width="20" height="20"></van-image>
                        <span style="margin-left: 0.4rem;">巡视要求</span>
                    </template>
				</van-cell>
				<van-collapse v-model="activeNames">
					<van-collapse-item :name="typeItem.workItemTypeId" v-for="typeItem in selTaskList" :title="typeItem.workItemTypeName" :key="typeItem.workItemTypeId">
						<div slot="title" style="display: flex;">
							<span class="line_green"></span>
							<span>{{ typeItem.workItemTypeName }}</span>
						</div>
						<van-cell
						  v-for="(item,index) in typeItem.workItemList"
						  clickable
						  :key="index"            
						  @click="deviceClickEvent(item)"
						  >
						  <div slot="title">
							  <div style="display: flex;justify-content: space-between;">
								  <span>{{item.workItemName}}</span>
							  </div>
							  <div>
								  <span style="color: #999999;">{{item.requireFinishTime | formate}}</span>
							  </div>
						  </div>
					  	</van-cell>
					</van-collapse-item>
				</van-collapse>
            </div>
		</div>

		<van-row class="btn-wrapper">
			<div class="btn-left"  @click="cancel">
				<van-image :src="icon.iconBack" width="22" height="22"></van-image>
				<div style="font-size: 0.9315rem;color:#666;">返回</div>
			</div>
			<div style="flex:1">
				<van-button style="width: 70%;"  @click="registTask" color="#17B49B" type="primary" size="small">开始登记</van-button>
			</div>
		</van-row>

		<!-- 反馈组件 选择人员-->
		<van-popup class="selSub" round close-on-click-overlay v-model="showPerson" position="bottom" @close="showPerson=false">
			<selPople :userList="userList"
			@comfirmPerson="personConfirm" :single="single"
			@closePersonPage="showPerson=false"></selPople>
		</van-popup>
		
		<!-- 时间类型选择器 -->
		<van-popup round close-on-click-overlay v-model="isDatePicker" position="bottom">
			<van-datetime-picker v-model="currentDate" title="选择日期" 
			:min-date="minDate"
			:formatter="formatter"
  			:max-date="maxDate"
			@confirm="onConfirm" @cancel="isDatePicker=false" type="datetime">
				<template slot="default">
					<van-nav-bar title="登记信息"  left-arrow @click-left="back">
						<template slot="right">
							<div class="parent-circle">
								<div class="child-circle"></div>
							</div>
						</template>
					</van-nav-bar>
				</template>
			</van-datetime-picker>
		</van-popup>
		
		<!-- 签名信息 -->
		<van-popup v-model="showSign" close-icon="rise-pop-close" round
		:style="{height: '900',width: '90%'}">
			<sign-name @closesign="closePerson" @personback="personBack"></sign-name>
		</van-popup>
		<!-- pop end -->
	</article>
</template>

<script type="text/javascript">
	import { Tabbar, TabbarItem ,Tag } from 'vant';
	import {registerMaintainRecord} from '../../api/deviceProfect';
	import Theader from "../component/header"
	import {UploadSignPhoto} from '../../api/common';
	import selPople  from "@/components/SelPeople.vue"
	import SignName from './SignName.vue';
	import Util from "@/utils/util"
	export default {
		name: 'protectFinish',
		components: {
			SignName,
			selPople,
			Theader
		},
		props:{
			selTaskList: {
				type: Array,
				default: function() {
					return []
				}
			},
		},
		data() {
			return {
				baseV: "down",
				title: "登记信息",
                registData:{
					startTime: "",//开始时间
					endTime: "",//结束时间
					MAKER: "",
					CHECKER: "",
					remark: "",//备注
					result: "合格",//结论
				},
				single:false,//人员true单选 false多选
				timeType: "",
                isDatePicker:false,//日期显示开关
				currentDate: new Date(),
				activeNames: [],
				userList: [],
				//工作人员列表
				workPersonList: [], 
				//负责人员列表
				mainPersonList: [],
				//维护人员列表
				maintainerList: [],
				showSign:false,//签名开关
				showPerson:false,//人员选择开关
				personType: "",//区分 负责人 工作人员
				arrIndex: "",//数组下标
				icon: {
					iconDate: require("../../../../assets/tour/icon-date.png"),
					iconTitle: require("../../../../assets/tour/icon-title.png"),
					iconBack: require("../../../../assets/tour/icon_back.png"),
				},
				maintainPerson: "",
				userInfo:{},
				minDate: new Date(new Date().getFullYear()-2,new Date().getMonth()+1,new Date().getDay()),
				maxDate: new Date(new Date().getFullYear()+2,new Date().getMonth()+1,new Date().getDay())
			}
		},
		computed: {
			showTime() {
				var showT ="0时0分";
				if(this.registData.startTime && this.registData.endTime) {
					var start = new Date(this.registData.startTime).getTime();
					var end = new Date(this.registData.endTime).getTime();
					var total = (end -start)/1000;
					if(end > start) {
						var hour = parseInt(total/(60*60));
						var min =  ((total - hour*60*60)/60);
						
					}
					showT = (hour? hour+"时":"") + (min? min+"分":"");
					showT ? showT: "0分";
				}
				return showT;
			}
		},
		methods: {
			/**
			* @description:箭头方向
			* @param {*}
			* @return {*}
			*/
			arrowDirection() {
				this.baseV = this.baseV == "down" ? "up" : "down";
			},
			//日期格式
			formatter(type, val) {
				if (type === 'year') {
					return val + '年';
				}
				if (type === 'month') {
					return val + '月';
				}
				if (type === 'day') {
					return val + '日';
				}
				if (type === 'hour') {
					return val + '时';
				}
				if (type === 'minute') {
					return val + '分';
				}
				return val;
			},
			//确认按钮
			confirm(){
				this.$emit("confirm");
			},
			//取消
			cancel() {
				this.$emit("cancel")
			},
            onConfirm(val){
				this.isDatePicker = false;
				if(this.timeType == 'sTime') {
					this.registData.startTime = Util.DateUtil.getFormatDateByLong(val,'yyyy-MM-dd hh:mm')
				}else{
					this.registData.endTime = Util.DateUtil.getFormatDateByLong(val,'yyyy-MM-dd hh:mm')
				}
			},
			
			//签名人员回调
			personBack(signImg) {
				this.showSign = false;
				if(this.personType == 'workPersonList') {
					this.workPersonList[this.arrIndex]['signImg'] = signImg;
				}else{
					this.mainPersonList[this.arrIndex]['signImg'] = signImg;
				}
			},
			//关闭签名组件
			closePerson() {
				this.showSign = false;
			},
			//选择时间
            onClickRightIcon(data){
				this.timeType = data;
                this.isDatePicker=true;
			},
			/**
			 * 返回
			 */
			 back(){
				this.$emit("cancel");
			},
			/**
			* @description: 显示人员
			* @param {*}
			* @return {*}
			*/
			personBtn(val){
				this.showPerson=true;
				this.personType = val;
				if(val == "workPersonList") {//工作人员
					this.single = false;
					console.log("this.workPersonList",this.workPersonList)
					this.userList = this.workPersonList;
				}else if(val == "mainPersonList") {//工作负责人
					this.single = true;
					console.log("this.mainPersonList",this.mainPersonList)
					this.userList = this.mainPersonList;
				}else{//维护人员
					this.single = false;
					this.userList = this.maintainerList;
				}
			},
			/**
			* @description: 签名点击事件
			* @param {*}
			* @return {*}
			*/
			signBtn(name,index){
				this.personType = name;
				this.arrIndex = index;
				this.showSign=true;
			},
			/**
			* @description: 删除签名
			* @param {*}
			* @return {*}
			*/
			delSignBtn(name,index) {
				var self = this;
				if(name == "workPersonList") {
					this.workPersonList[index]["signImg"] = "";
					this.workPersonList = JSON.parse(JSON.stringify(this.workPersonList))
				}
				if(name == "mainPersonList") {
					this.mainPersonList[index]["signImg"] = "";
					this.mainPersonList = JSON.parse(JSON.stringify(this.mainPersonList))
				}
			},
			//人员确认页面
			personConfirm(person) {
				console.log("person===",person);
				this.showPerson = false;
				if(person.length == 0) {
					return;
				}
				//工作人员
				if(this.personType == 'workPersonList') {
					//重新添加 保留上次签名信息
					for(var item of person) {
						for(var per of this.workPersonList) {
							if(per.userId == item.userId) {
								item["signImg"] = per.signImg;
								break;
							}else{
								item["signImg"] = "";
							}
						}
					}
					this.workPersonList = JSON.parse(JSON.stringify(person));
				}else if(this.personType == 'mainPersonList'){
				//工作负责人
					for(var item of person) {
						for(var per of this.mainPersonList) {
							if(per.userId == item.userId) {
								item["signImg"] = per.signImg;
								break;
							}else{
								item["signImg"] = "";
							}
						}
					}
					this.mainPersonList = JSON.parse(JSON.stringify(person));
				}else{
					//维护人员
					this.maintainerList = person;
					this.maintainPerson = person.map(item => item.userName).join(",")
				}
			},
			/**
			* @description: 登记维护任务
			* @param {*}
			* @return {*}
			*/
			registTask() {
				if(Util.baseUtil.isEmptyString(this.registData.startTime)) {
					this.$Toast.fail("请选择开始时间!")
					return;
				}
				if(Util.baseUtil.isEmptyString(this.registData.endTime)) {
					this.$Toast.fail("请选择结束时间!")
					return;
				}
				var start = new Date(this.registData.startTime).getTime();
				var end = new Date(this.registData.endTime).getTime();
				if(start > end) {
					this.$Toast.fail("开始时间不能大于结束时间!")
					return;
				}
				if(this.maintainerList.length == 0) {
					this.$Toast.fail("请选择维护人员!")
					return;
				}

				if(this.workPersonList.length == 0) {
					this.$Toast.fail("请选择工作人员!")
					return;
				}
				for(var workPerson  of this.workPersonList) {
					if(!workPerson.signImg) {
						this.$Toast.fail("工作人员未签名!")
						return;
					}
				}
				if(this.mainPersonList.length == 0) {
					this.$Toast.fail("请选择工作负责人员!")
					return;
				}
				for(var mainPerson  of this.mainPersonList) {
					if(!mainPerson.signImg) {
						this.$Toast.fail("负责人员未签名!")
						return;
					}
				}
				if(Util.baseUtil.isEmptyString(this.registData.result)) {
					this.$Toast.fail("请填写结论!")
					return;
				}
				this.uploadSignImg();
			},
			/**
			* @description: 上传签名图片
			* @param {*}
			* @return {*}
			*/
			async uploadSignImg() {
				var imgList =  this.workPersonList.concat(this.mainPersonList);
				console.log(this.workPersonList)
				console.log(this.mainPersonList)
				var signUuid = imgList.map(item => {
					return Util.baseUtil.dataUrlToFile(item.signImg)
				})
				console.log("signUuid",signUuid)
				this.$Toast.loading({
					duration: 0,//展示时长 0不会消失
					message: "签名上传中...",
					forbidClick: true,//是否禁止背景点击
					overlay: true//是否显示背景遮罩层
				})
				try {
                    var signFile = await Promise.all(signUuid);
                    var uuidArr = signFile.map(file => {
						var formData = new FormData; 
						formData.append("file", file) //文件流
                        formData.append("userId",this.userInfo.userId)
                        formData.append("source","1")//1 维护  0 缺陷  2 隐患
                        return UploadSignPhoto(formData)
                    })
					var list = await Promise.all(uuidArr);
					//工作负责人签名
					var personInChargeSign = list[list.length-1].data;
					//工作人员签名id
					var maintainRecordWorkerList = [];
					this.workPersonList.map((item,index) => {
						maintainRecordWorkerList.push({
							workerId: item.userId,
							workerName: item.userName,
							workerSignPic: list[index].data
						})
					})
					this.$Toast.clear();
					this.registerMaintainRecord(maintainRecordWorkerList,personInChargeSign);
                } catch (error) {
                    this.$Toast.clear();
                    console.log("签名上传失败，请稍后再试!") 
                }
			},
			/**
			* @description: 维护信息确认
			* @param {*}
			* @return {*}
			*/
			registerMaintainRecord(workerSign,mainSign) {
				var self = this,startTime="",endTime="",workId=[],maintainPerList=[];
				startTime = new Date(this.registData.startTime).getTime();
				endTime = new Date(this.registData.endTime).getTime();
				this.maintainerList.forEach(item => {
					maintainPerList.push({
						accendantId: item.userId,
						accendantName: item.userName
					})
				})
				this.selTaskList.map(item => {
					if(item.workItemList && item.workItemList.length > 0) {
						var list = item.workItemList.map(work => work.maintainRecordId)
						workId.push(...list);
					}
				})
				var params = {
					maintainRecordIdList: workId,//任务列表
					userId: this.userInfo.userId,//用户id
					roleCode: "",//用户角色
					conclusion: this.registData.result,
					remarks: this.registData.remark,
					startTime: startTime,//开始时间
					endTime: endTime,//结束时间
					maintainerList: maintainPerList,//维护人员
					maintainRecordWorkerList: workerSign, //工作人员签名
					personInChargeSign: mainSign,//工作负责人员签名
					personInChargeName: this.mainPersonList[0].userName,//工作负责人员名称
					personInChargeId:this.mainPersonList[0].userId,//工作负责人员id
				}
				console.log("params",params)
				this.$Toast.loading({
						duration: 0,//展示时长 0不会消失
						message: "维护信息登记中...",
						forbidClick: true,//是否禁止背景点击
						overlay: true//是否显示背景遮罩层
					})
				registerMaintainRecord(params).then(data => {
					self.$Toast.clear();
					if(data.success) {
						self.confirm();
						self.$Toast.success(data.msg)
					}else{
						self.$Toast.fail(data.msg)
					}
				}).catch(err => {
					self.$Toast.fail(err)
				})
			},
			render() {
				this.maintainerList.push({
					userId: this.userInfo.userId,
					userName: this.userInfo.userName
				})
				this.maintainPerson = this.userInfo.userName;//维护人，默认登录人
				this.workPersonList.push({//默认工作人员
					userId: this.userInfo.userId,
					userName: this.userInfo.userName,
					signImg: ""
				})
			}
		},
		filters: {
			formate(val) {
				return Util.DateUtil.getFormatDateByLong(val,'yyyy年MM月dd日')
			}
		},
		mounted() {
			var userInfo = localStorage.getItem("userInfo");
			this.userInfo = JSON.parse(userInfo);
			// this.registData.startTime = Util.DateUtil.getFormatDateByLong(new Date().getTime(),'yyyy-MM-dd hh:mm');
			// this.render();
		},
		
		created() {
			
		},
		
	}
</script>

<style scoped>
	article {
		display: flex;
		flex-direction: column;
		height: 100vh;
        font-family: 微软雅黑;
		background: #F5F6F7;
		margin: 0 auto;
		width: 100%;
	}
	.title-time{
		margin-top: 45px;
		text-align: center;
		background: #f5e5e8;
		height: 2.5rem;
		line-height: 2.5rem;
		font-size: 15px;
		color: #333;
	}
	.beizhu .left, .jielun .left{
		font-size: 0.8125rem;
		padding: 0 15px;color:#666;margin-top: 15px;
	}
	.beizhu .right, .jielun .right{
		font-size: 0.8125rem;
		margin: 15px;border-radius: 5px;
	}
	.textarea-content{
		border: 1px solid #E2E2E2;color:#999;
	}
	.btn-wrapper{
		position: fixed;
		width: 100%;
		bottom: 5px;
		display: flex;
		align-items: center;
		justify-content: center;
		text-align: center;
		background: #fff;
    	padding: 1rem;
	}
	.workAll{
		position: absolute;
    	right: 12.7%;
		top:12px;
	}
	.btn-left{
		width: 30%;
	}
	.doc-wrapper{
        margin: 0.7rem;
        box-shadow: 0px 0px 4px 2px #e0e0e0;
        border-radius: 0.3rem;
        background: #fff;
        padding-bottom: 1rem;
	}
	/deep/ .van-cell{
		padding: 6px 16px;
	}
	/deep/ .van-field__label{
		width: 6.5rem;
		font-size: 13px;
    	color: #666;
	}
	/deep/ .van-cell__value{
		color: #333333;
		font-size: 13px;
	}
	.sign-right /deep/ .van-cell__value{
		background: #F5F6F7;
	}
	.sign-right /deep/ .van-cell__right-icon{
		background: #F5F6F7;
		margin-left: 0px;
	}
	.item-title /deep/ .van-cell__title{
        display: flex;
        align-items: center;
        font-weight: bold;
        font-size: 0.9375rem;
    }
</style>